# -*- coding: UTF-8 -*-

from odoorpc2 import RPC

base_url = 'http://192.168.56.114:8069'

timeout = 50000

addons_list = ['odoorpc2/addons']


dbname = 'T1'
dbname = 'T2'
username = 'admin'
password = '123456'

rpc = RPC(base_url, timeout, dbname, addons_list)


def test_o2m():
    print('test_o2m')
    action_id = 'base.action_country'
    tree = rpc.env.treeview(action_id)
    tree.load_fields()
    res = tree.search_read(domain=[], limit=1)
    print('test_o2m tree', res)

    one = res[0]
    res_id = one['id']
    form = rpc.env.formview(action_id)
    form.load_fields()

    view_info = form.view_info
    print('test_o2m view_info', view_info)

    state_ids_field_info = form.fields['state_ids']
    print('test_o2m state_ids_field_info', state_ids_field_info)

    state_ids_relation = rpc.env.relation(
        state_ids_field_info, parent=view_info)

    state_ids_relation_views = state_ids_relation.load_views()
    print('test_o2m state_ids_relation_views', state_ids_relation_views)

    record = form.read(res_id)
    print('test_o2m form', record)

    form.set_editable(record)

    state_ids = record['state_ids']
    print('test_o2m state_ids', state_ids)

    state_ids_treeview = state_ids_relation.tree
    state_ids_records = state_ids_treeview.read(state_ids)
    print('test_o2m state_ids_records', state_ids_records)

    state_ids_formview = state_ids_relation.form

    res = state_ids_formview.onchange_new({'record': record, 'values': {}})
    print('test_o2m state_ids_ new ', res)
    res = state_ids_formview.onchange('name', 'aaa')
    print('after o2m name edit:', res)

    res = state_ids_formview.onchange('code', 'a')
    print('after o2m code edit:', res)

    on2_one = state_ids_formview.commit()
    print('after o2m commit:', on2_one)

    state_ids_values_list = []

    res = state_ids_treeview.commit(
        state_ids_records, state_ids_values_list, on2_one)
    print('o2m tree commit:', res)

    o2m_values_onchange = res['values_onchange']
    res = form.onchange('state_ids', o2m_values_onchange)
    print('form onchange:', res)

    res_id = form.commit()
    print('form commit:', res_id)

    res = form.read(res_id)
    print('form read:', res)


def test():
    res = rpc.login(username,  password)

    test_o2m()


test()
